package com.redisson.controller;

import com.redisson.compoent.lock.RedisLock;
import com.redisson.compoent.rateLimit.RedisRateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.ReentrantLock;

@RestController
public class RedissonController {
    @Autowired
    private RedisLock redisLock;
    @Autowired
    private RedisRateLimiter redisRateLimiter;

    @GetMapping("testLock")
    public String testLock() {
        redisLock.doSomethingWithLock();
        return "success";
    }

    @GetMapping("testLimit")
    public String testLimit() {
        for (int i = 0; i < 100; i++) {
            redisRateLimiter.limitRate("testLimit");
        }
        return "success";
    }


    // 创建锁对象
    private static final ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        // 定义线程任务
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 加锁
                lock.lock();
                try {
                    // 打印执行线程的名字
                    System.out.println("线程:" + Thread.currentThread().getName());
                } finally {
                    // 释放锁
                    lock.unlock();
                }
            }
        };
        // 创建多个线程
        for (int i = 0; i < 10; i++) {
            new Thread(runnable).start();
        }
    }




}

